<?php
App::uses('AppController', 'Controller');

class ShopManageController extends AppController {
	var $helpers = array('Paginator','Html');
	public $user = "";
	var $components = array('Files');
	public function beforeFilter() {
		parent::beforeFilter();
		$this->user = parent::checkAdminOrManagerLogin();
	}
	/**
	* hiển thị toàn bộ shop
	*/
	public function admin_index() {
		$this -> loadModel('Shop');
		$this->paginate = array(
                                'limit' => ITEM_PER_PAGE,
                                'order' => array('id' => 'desc'),
                             );
		$conditions = array("Shop.deleted" => 0);
        $data = $this->paginate("Shop", $conditions);
        $data = $this->addTimePostColumn($data);
        $this->set("data",$data);
		$this->set("title_for_layout","Quản lý shop");
	}
	public function admin_delete($id){
		$this -> loadModel('Shop');
		$data =$this->Shop-> findShopById($id);
		if(!empty($data)){
			$this->Shop->updateFieldDeleteTrue($data, $this->user["id"]);
		}
		$this->redirect(array('action' => 'index'));
	}
	public function admin_edit($id){
		$this->theme = 'Default';
		$this -> layout = 'layoutNoMenuLeft';
		$this->set("action","/admin/ShopManage/edit");
		
		$this->loadModel('Shop');
		$this->loadModel('RootCategory');
		$this->loadModel('ShopLocation');
		
		$this->set('title_for_layout','Chỉnh sửa gian hàng');
		
		$this->set('rootCategories',$this -> RootCategory->findAllData());
		
		$conditions = array("Shop.id" => $id, "Shop.deleted" =>0);
		
		$data = $this->Shop->find('first', array('conditions' => $conditions));
		
		if(empty($data)){
			$this->redirect(array('action' => 'index'));
		}
		$shopId = $data['Shop']['id'];
		$shopLocation = $this->ShopLocation->find('all',array(
			'conditions' => array('shop_id' => $data['Shop']['id'], "deleted"=>0),
			'order' => array('location_id' => 'asc')
			));
		$this->set("shopLocation",$shopLocation);
		
		$n = count($shopLocation);
		$arrLocationId = array();
		for($i = 0; $i < $n; $i++){
			array_push($arrLocationId, $shopLocation[$i]["ShopLocation"]["location_id"]);
		}
		$arrLocation = array(0,1,2);
		$arr =  array();
		// lấy danh sách khu vuc chưa dang ký truoc đó
		for($j = 0; $j < count($arrLocation); $j++){
			$r = array_search($arrLocation[$j], $arrLocationId);
			if(is_int($r) == false){
				array_push($arr, $arrLocation[$j]);
			}
		}
		$this->set("locationNew", $arr);
		$this -> set("data", $data['Shop']);
		
		if ($this -> request -> is('post')) {
			
			$update = $this -> data;
			
			/*echo "<pre>";
			print_r($update);
			exit;*/
			if($update['banner_image']['name'] != ""){
				$update['banner_image'] = $this->Files->uploadFile(UPLOAD_IMG_SHOP, $update['banner_image']['tmp_name'], ROOT_IMG_SHOP, $update['banner_image']['name']);
				$this->Files->deleteFile(WWW_ROOT.$update['banner_image_old']);
			}else{
				unset($update['banner_image']);
			}
			
			if($update['logo_image']['name'] != ""){
				$update['logo_image'] = $this->Files->uploadFile(UPLOAD_IMG_SHOP, $update['logo_image']['tmp_name'], ROOT_IMG_SHOP, $update['logo_image']['name']);
				$this->Files->deleteFile(WWW_ROOT.$update['logo_image_old']);
			}else{
				unset($update['logo_image']);
			}
			
			$update['updated_by'] = $this->user['id'];//lấy id của user login
			$update['updated_at'] = date("Y-m-d H:i:s"); 
			
			$this->Shop->save($update);
			
			//shop location
			$shopLocation = $update['shopLocation'];
			$shopLocationUpdate = array();
			for($i=0; $i<3; $i++) {
				if($shopLocation[$i]['phone'] != ""){
					$shopLocation[$i]['shop_id'] = $shopId;
					$shopLocation[$i]['deleted'] = 0;
					$shopLocation[$i]['created_by'] = $this->user['id'];
					$shopLocation[$i]['created_at'] = date("Y-m-d H:i:s");
					$shopLocation[$i]['updated_by'] = $this->user['id'];
					$shopLocation[$i]['updated_at'] = date("Y-m-d H:i:s");
					array_push($shopLocationUpdate, $shopLocation[$i]);
				}
				
				if($shopLocation[$i]['phone'] == "" && !empty($shopLocation[$i]['id'])){
					$delete = array();
					$delete['deleted'] = 1;
					$delete['id'] = $shopLocation[$i]['id'];
					
					array_push($shopLocationUpdate, $delete);
				}
			}
			if(count($shopLocationUpdate) > 0){
				$this->ShopLocation->saveMany($shopLocationUpdate);
			}
			
			$this->redirect(array('action' => 'index'));
		}
		$this -> render('/StallsAdd/edit');
	}
	/**
	 * Add time post column for lists
	 *
	 * @author VuLee
	 */
	private function addTimePostColumn($data){
		for ($i=0; $i < count($data); $i++) { 
			$data[$i]['Shop']['time_post'] = $this->calculateTimePost($data[$i]['Shop']['updated_at']);
		}
		return $data;
	}

	/**
	 * Calculate time post
	 *
	 * @author VuLee
	 */
	private function calculateTimePost($old_date){
		date_default_timezone_set('Asia/Ho_Chi_Minh');
		$current_date = date('Y-m-d H:i:s');
		$old_date = date_create($old_date);

		$current_date = date_create($current_date);
		$diff = date_diff($old_date, $current_date);

		$year = $diff->y;
		if ($year > 0) {
			return $year." năm";
		}

		$month = $diff->m;
		if ($month > 0) {
			return $month." tháng";
		}

		$day = $diff->d;
		if ($day > 0) {
			return $day." ngày";
		}

		$hour = $diff->h;
		if ($hour > 0) {
			return $hour." giờ";
		}

		$minute = $diff->i;
		$hour = $diff->h;
		if ($minute > 0) {
			return $minute." phút";
		}
		return "Mới đây";
	}

}
?>